package es;

import com.google.protobuf.Internal;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.search.aggregations.bucket.histogram.ExtendedBounds;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.aggregations.bucket.range.Range;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.avg.Avg;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class ESTest {

    @Test
    public void groupQuery() throws Exception {
        Settings settings = Settings.builder().put("cluster.name", "application").put("client.transport.sniff", true).build();
        /*TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddresses(new TransportAddress(InetAddress.getByName("172.16.85.215"), 9300));*/
        TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddresses(new InetSocketTransportAddress(InetAddress.getByName("172.16.85.215"), 9300));

        //先按address进行分组, 再在每个address分组内按年龄的年份进行分组, 最后计算每个组的平均年龄
        TermsAggregationBuilder aggregation = AggregationBuilders.terms("group_address")
                .field("address")
                .subAggregation(
                        AggregationBuilders.dateHistogram("group_birthday")
                                .field("birthday")
                                .dateHistogramInterval(DateHistogramInterval.YEAR)
                                .minDocCount(1)
                                .subAggregation(AggregationBuilders.avg("avg_age").field("age"))
                );

        SearchResponse response = client.prepareSearch("lib1").setTypes("user").addAggregation(aggregation)
                .execute().actionGet();

        System.out.println("状态: " + response.status());
        Map<String, Aggregation> groupAddressMap = response.getAggregations().asMap();
        Terms addressTerms = (Terms) groupAddressMap.get("group_address");
        for (Terms.Bucket address : addressTerms.getBuckets()) {
            System.out.println(address.getKey() + " " + address.getDocCount());
            Histogram birthday = address.getAggregations().get("group_birthday");
            for (Histogram.Bucket birthdayBucket : birthday.getBuckets()) {
                System.out.println(birthdayBucket.getKey() + " " + birthdayBucket.getDocCount());
                Avg avg = birthdayBucket.getAggregations().get("avg_age");
                System.out.println("平均年龄: " + avg.getValue());
                System.out.println("===========================");
            }
        }
        //关闭连接
        client.close();
    }


    @Test
    public void testQuery() throws Exception {
        Settings settings = Settings.builder().put("cluster.name", "comment").put("client.transport.sniff", true).build();
        TransportClient client = new PreBuiltTransportClient(settings).addTransportAddresses(new InetSocketTransportAddress(InetAddress.getByName("10.2.98.164"), 9300));
        
        SearchResponse response = client.prepareSearch("user_index").setTypes("user").setQuery(QueryBuilders.matchAllQuery())
                .setScroll(new TimeValue(10000))
                .setSize(2).addSort("age", SortOrder.DESC).addSort("id", SortOrder.ASC).get();
        int count = 0;
        /*do{
            System.out.println("第 " + ++count + " 次查询ES............." + " 总数: " + response.getHits().totalHits);
            SearchHit[] hits = response.getHits().getHits();
            if(hits.length <= 0){
                return;
            }
            for (SearchHit hit : hits){
                System.out.println(hit.getSourceAsString());
            }
            System.out.println(response.getScrollId());
            response = client.prepareSearchScroll(response.getScrollId()).setScroll(new TimeValue(10000)).execute().actionGet();
        }while (response.getHits().getHits().length > 0);*/
        
        
        SearchResponse response1 = client.prepareSearchScroll("DnF1ZXJ5VGhlbkZldGNoAwAAAAABvNNPFko0T1JNTDNOUWFpbU5Bd0dPUFBOMFEAAAAAAZ2ICBYxVk5mc05OM1FBYXFrcFIxeTZNYWd3AAAAAAGdiAkWMVZOZnNOTjNRQWFxa3BSMXk2TWFndw==")
                .setScroll(new TimeValue(1000)).get();
        SearchHit[] hits = response.getHits().getHits();
        System.out.println(hits.length);
        
        
        System.out.println("查询数据结束....................");
        //关闭连接
        client.close();
    }
    
    public static void main(String[] args) {
        try {
            System.out.println("main...............");
            return;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            System.out.println("finally.............");
        }
    }
}
